import uuid
from datetime import datetime
from app.utils.mongo import db  # 导入数据库连接

checkin_collection = db['checkin_records']
question_collection = db.questions
stamp_collection = db['electronic_stamps']


class CheckinRecord:
    @staticmethod
    def create_record(data):
        """创建新打卡记录"""
        record_id = str(uuid.uuid4())
        
        # 确保时间格式正确
        now = datetime.utcnow()
        time_str = now.strftime('%Y-%m-%dT%H:%M:%S.000+00:00')
        
        record = {
            'id': record_id,
            'userId': data['userId'],  # 来自JWT的用户ID
            'buildingId': data['buildingId'],
            'buildingName': data['buildingName'],
            'sceneryName': data.get('sceneryName', ''),
            'checkinTime': time_str,
            'images': data.get('images', []),
            'comment': data.get('comment', ''),
            'hasAnswered': False,
            'score': 0,
            'location': data.get('location', {}),
            'stampId': '',
            'stampUrl': '',
            'createdAt': time_str,
            'updatedAt': time_str
        }
        
        # 创建电子印章
        stamp = ElectronicStamp.create_stamp({
            'userId': data['userId'],
            'buildingId': data['buildingId'],
            'buildingName': data['buildingName']
        })
        
        if stamp:
            record['stampId'] = stamp['id']
            record['stampUrl'] = stamp['url']
        
        result = checkin_collection.insert_one(record)
        return record if result.inserted_id else None

    @staticmethod
    def get_records_by_user(user_id, page=1, limit=10):
        """根据用户ID获取打卡记录，支持分页"""
        skip = (page - 1) * limit
        records = list(checkin_collection.find({'userId': user_id})
                      .sort('checkinTime', -1)
                      .skip(skip)
                      .limit(limit))
        total = checkin_collection.count_documents({'userId': user_id})
        return {
            'records': records,
            'total': total,
            'page': page,
            'limit': limit,
            'pages': (total + limit - 1) // limit
        }
    
    @staticmethod
    def get_record_by_id(record_id):
        """根据记录ID获取打卡记录"""
        return checkin_collection.find_one({'id': record_id})
    
    @staticmethod
    def update_answer_status(record_id, score):
        """更新打卡记录的答题状态和分数"""
        now = datetime.utcnow()
        updated_time = now.strftime('%Y-%m-%dT%H:%M:%S.000+00:00')
        result = checkin_collection.update_one(
            {'id': record_id},
            {'$set': {
                'hasAnswered': True,
                'score': score,
                'updatedAt': updated_time
            }}
        )
        return result.modified_count > 0
    
    @staticmethod
    def get_checkin_locations():
        """获取所有打卡地点的统计信息"""
        locations = checkin_collection.aggregate([
            {
                '$group': {
                    '_id': '$buildingId',
                    'buildingName': {'$first': '$buildingName'},
                    'count': {'$sum': 1},
                    'locations': {'$first': '$location'}
                }
            },
            {
                '$project': {
                    'buildingId': '$_id',
                    'buildingName': 1,
                    'count': 1,
                    'location': '$locations',
                    '_id': 0
                }
            }
        ])
        return list(locations)


class Question:
    @staticmethod
    def get_questions_by_building(building_id, limit=5):
        """根据建筑ID获取问题"""
        return list(question_collection.find({'buildingId': building_id}).limit(limit))
    
    @staticmethod
    def get_by_building_type(building_type, limit=5):
        """根据建筑类型获取问题"""
        return list(question_collection.find({'buildingType': building_type}).limit(limit))
    
    @staticmethod
    def get_by_ids(question_ids):
        """根据问题ID列表获取问题"""
        return list(question_collection.find({'id': {'$in': question_ids}}))
    
    @staticmethod
    def create_question(data):
        """创建问题"""
        question_id = str(uuid.uuid4())
        now = datetime.utcnow()
        time_str = now.strftime('%Y-%m-%dT%H:%M:%S.000+00:00')
        question = {
            'id': question_id,
            'buildingId': data['buildingId'],
            'buildingType': data.get('buildingType', ''),  # 新增建筑类型字段
            'content': data['content'],
            'options': data.get('options', []),
            'correctAnswer': data['correctAnswer'],  # 修正字段名，与验证逻辑一致
            'score': data.get('score', 10),
            'createdAt': time_str,
            'updatedAt': time_str
        }
        result = question_collection.insert_one(question)
        return question if result.inserted_id else None


class ElectronicStamp:
    @staticmethod
    def create_stamp(data):
        """创建电子印章"""
        stamp_id = str(uuid.uuid4())
        now = datetime.utcnow()
        time_str = now.strftime('%Y-%m-%dT%H:%M:%S.000+00:00')
        # 这里假设印章URL可以根据用户ID和建筑ID生成，实际项目中可能需要结合文件存储服务
        stamp_url = f"/stamps/{stamp_id}.png"
        stamp = {
            'id': stamp_id,
            'userId': data['userId'],
            'buildingId': data['buildingId'],
            'buildingName': data['buildingName'],
            'url': stamp_url,
            'createdAt': time_str
        }
        result = stamp_collection.insert_one(stamp)
        return stamp if result.inserted_id else None
    
    @staticmethod
    def get_stamps_by_user(user_id):
        """根据用户ID获取电子印章"""
        return list(stamp_collection.find({'userId': user_id}).sort('createdAt', -1))